<template>
  <div class="table-wrapper edit-wrapper" v-loading="loading">
    <!-- height="400px"     日期  select 单机     input双击-->
    <el-scrollbar ref="scrollRef" @scroll="scrollFun">
      <!-- content: "";
            display: block;
            clear: both; float: left;width: 0-->

      <div class="scroolY" style="float: left; width: 0">
        <div class="merak_table edit_table" ref="editTableRef">
          <table class="scrollTable" id="excelTableMerak" @mousedown="handleMouseDown" @mouseup="handleMouseUp">
            <colgroup>
              <col width="50px" />
              <col v-if="selection" width="50px" />
              <col v-for="(column, cKey) in headers" :key="cKey" :width="`${column.width}px`" />
              <col width="100px" v-if="$slots.handle" />
            </colgroup>
            <thead>
              <!-- <headerCell></headerCell> -->
              <tr class="thead-row">
                <th class="table-number table-fixed-column table-fixed-column-left table-cell-fixed" v-if="number">
                  <div class="opration-cell"></div>
                </th>
                <th class="table-checkbox table-fixed-column table-fixed-column-left table-cell-fixed" v-if="selection">
                  <qfCheckbox
                    :isChecked="allChecked"
                    :indeterminate="isIndeterminate"
                    @change.native.stop="allCheckedFun"
                  ></qfCheckbox>
                </th>
                <th
                  v-for="(column, cKey) in headers"
                  :key="cKey"
                  @mousedown.native.stop="startDrag(cKey)"
                  @click="e => acticeBgRow(e, column, cKey)"
                  :style="{ width: column.width }"
                  class="table-fixed-column"
                  :class="{ 'table-cell-fixed table-fixed-column-left': column.fixed == 'left', columnTh: column.selection }"
                >
                  <div class="header-cell" :style="{ width: column.width }">
                    {{ column.name }}
                  </div>
                  <div class="cell-resizable" v-if="!!dragDrop && !(column.fixed == 'left')"></div>
                </th>
                <!-- //操作列 固定 -->
                <!-- table-cell-fixed-right table-box-shadow-right -->
                <th class="table-cell-fixed-right table-fixed-column-right" v-if="$slots.handle">
                  <!-- :style="{ width: handle.width }" -->
                  <div class="opration-cell">操作</div>
                </th>
              </tr>
            </thead>
            <tbody ref="tbodyRef" class="tbodyContent">
              <!-- <columnCell></columnCell> -->

              <tr
                v-for="(row, rsIndex) in columnsTableData"
                :key="rsIndex"
                class="tbody-row"
                :class="{ selectionTr: row.selection }"
                :rowsIndex="row.index"
                :title="$t('merak.dobule_click_edit')"
              >
                <td class="table-cell table-number table-cell-fixed table-fixed-rows-left" v-if="number">
                  <!-- # xuliehao  -->
                  <div class="cell-nowrap">{{ row.index + 1 }}</div>
                </td>
                <td class="table-cell table-checkbox table-cell-fixed table-fixed-rows-left" v-if="selection">
                  <qfCheckbox :isChecked="row.selection" @change.native.stop="e => checkItemFun(e, rsIndex, row)"> </qfCheckbox>
                </td>
                <!-- 循环列      @dblclick.stop="column.data?.type=='input'?dbEditClick(column,row,rsIndex):''"
                            @click.stop="column.type=='input'?onceEditClick(column,row,rsIndex):''"-->
                <td
                  v-for="(column, rIndex) in headers"
                  :key="rIndex"
                  class="table-cell"
                  :data-Obj="`{&quot;indexCell&quot;:&quot;${rIndex}&quot;,&quot;indexRow&quot;:&quot;${rsIndex}&quot;,&quot;id&quot;:&quot;${
                    row._id
                  }&quot;,&quot;key&quot;:&quot;${column.key}&quot;,&quot;errTip&quot;:&quot;${
                    row.data[column.key]?.errTip
                  }&quot;}`"
                  :class="{
                    'table-cell-fixed table-fixed-rows-left': column.fixed == 'left',
                    edit_disable: !column.isEdit,
                    'err-tip': !column.fixed && row.data[column.key]?.errTip,
                    selectedRow: column.selection && row.selection
                  }"
                  @mouseover="handleMouseOver"
                  @mouseleave="handleMouseLeave"
                  @dblclick.stop="dbEditClick(column, row, rsIndex, rIndex, column.key)"
                  @click.stop="e => onceEditClick(e, column, row, rsIndex, rIndex, column.key)"
                >
                  <div class="err-tip-triangle" v-if="!column.fixed && row.data[column.key]?.errTip"></div>
                  <div class="cell-nowrap" :class="{ 'select-nureal': column.type == 'select' && !row.data[column.key]?.isEdit }">
                    <slot
                      v-if="column.isEdit && row.data[column.key]?.isEdit"
                      :name="column.key"
                      :scope="{ [column.key]: row.data[column.key], index: row.index, key: column.key }"
                    >
                      <div v-if="column.type == 'input'">
                        <qfInput
                          v-model="row.data[column.key].label"
                          :maxlength="Number(column?.length)"
                          @change="value => editFormChange(value, column, row, 'input')"
                        ></qfInput>
                      </div>
                      <div v-if="column.type == 'number'">
                        <qfInput
                          v-number
                          v-model="row.data[column.key].label"
                          :maxlength="Number(column?.length)"
                          @change="value => editFormChange(value, column, row, 'input')"
                        ></qfInput>
                      </div>
                      <div v-if="column.type == 'select'">
                        <el-select
                          filterable
                          clearable
                          :multiple="column.multiple"
                          v-model="row.data[column.key].value"
                          @change="value => editFormChange(value, column, row, 'select')"
                        >
                          <el-option
                            v-for="selectItem in column.values"
                            :key="selectItem.value"
                            :label="selectItem.label"
                            :value="selectItem.value"
                          />
                        </el-select>
                      </div>
                      <div v-if="column.type == 'date'">
                        <!-- 时间 -->
                        <el-date-picker
                          :teleported="false"
                          v-model="row.data[column.key].label"
                          type="date"
                          value-format="YYYY-MM-DD"
                          @change="value => editFormChange(value, column, row, 'date')"
                        />
                        <!-- -->
                      </div>
                    </slot>

                    <span v-else :title="row.data[column.key]?.label">
                      {{ row.data[column.key]?.label }}
                      <!-- col:{{column.selection}}  || row:{{row.selection}} -->
                    </span>
                  </div>
                </td>

                <!--   table-box-shadow-right v-if="handle.show"-->
                <td class="table-cell-fixed-right table-fixed-rows-right" v-if="$slots.handle">
                  <div class="cell-nowrap">
                    <slot name="handle" :row="row"></slot>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </el-scrollbar>

    <div class="error_div_tip">
      <div class="err_cont">
        <!-- <div class="tip_title">数据错误</div> -->
        <div class="errr_tip_content">
          <div class="err_tip_item"></div>
        </div>
      </div>
    </div>

    <!-- 右击编辑 -->
    <div id="context-menu" class="context-menu">
      <ul>
        <li id="view-details" @click="moreEditFun">批量编辑</li>
      </ul>
    </div>

    <!-- 右击编辑 -->

    <!-- 弹窗批量编辑 -->
    <div>
      <el-dialog v-model="moreEditDialogVisible" :title="`批量编辑『${moreEditColumnHeader?.name}』`" width="500">
        <div class="moreEditContent">
          <div v-if="moreEditColumnHeader.type == 'input'" style="width: 95%">
            <qfInput v-model="moreEditParams.label" @change="value => moreEditFormChange(value, 'input')"></qfInput>
          </div>
          <div v-if="moreEditColumnHeader.type == 'number'" style="width: 95%">
            <qfInput v-number v-model="moreEditParams.label" @change="value => moreEditFormChange(value, 'input')"></qfInput>
          </div>
          <div v-if="moreEditColumnHeader.type == 'select'">
            <el-select
              filterable
              clearable
              :multiple="moreEditColumnHeader.multiple"
              v-model="moreEditParams.value"
              @change="value => moreEditFormChange(value, 'select')"
            >
              <el-option
                v-for="selectItem in moreEditColumnHeader.values"
                :key="selectItem.value"
                :label="selectItem.label"
                :value="selectItem.value"
              />
            </el-select>
          </div>
          <div v-if="moreEditColumnHeader.type == 'date'">
            <!-- 时间 -->
            <el-date-picker
              style="width: 100%"
              :teleported="false"
              v-model="moreEditParams.label"
              type="date"
              value-format="YYYY-MM-DD"
              @change="value => moreEditFormChange(value, 'date')"
            />
            <!-- -->
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="moreEditDialogVisible = false">Cancel</el-button>
            <el-button type="primary" @click="confirmEdit"> Confirm </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import { toRef, toRefs, ref, reactive, computed, watch, h, nextTick, onMounted, useSlots, onUnmounted, defineExpose } from "vue";
import qfCheckbox from "../a-qfCheckbox/index.vue";
import qfInput from "../a-qfInput/index.vue";
import moreEditDialog from "./components/moreEditModal.vue";
import { useGlobalStore } from "@/stores/modules/global";
import dayjs from "dayjs";
import useDateFormat from "@/hooks/useDateFormat";
import { json } from "stream/consumers";
import { TurnOff } from "@element-plus/icons-vue/dist/types";
import { chownSync } from "fs";
const { format } = useDateFormat();
const globalStore = useGlobalStore();
const props = defineProps({
  //table 表格头部
  headData: {
    type: Array<any>,
    default: []
  },
  //table 表格数据
  tableData: {
    type: Array<any>,
    default: []
  },
  //table可编辑列类型   input双击 其余单击
  headConfig: {
    type: Object,
    default: {}
  },
  //是否可拖拽  默认显示
  dragDrop: {
    type: Boolean,
    default: true
  },
  //checkbox是否显示  默认不显示
  selection: {
    type: Boolean,
    default: false
  },
  //#虚列号是否显示  默认不显示
  number: {
    type: Boolean,
    default: true
  },
  //是否开启编辑 默认开启关闭虚拟
  editStatus: {
    type: Boolean,
    default: true
  },
  //开启虚拟加载后
  editStatusType: {
    type: Boolean,
    default: false
  }
});

console.log(props);

const draggArr = ref(null); //鼠标移动选中数据

const disabled = ref(false);
const scrollRef = ref(null);
const scrollInnerRef = ref(null);
const editTableRef = ref(null);

//#region 滚动位置

//滚动到顶部
const initTopScroll = () => {
  scrollRef.value!.setScrollTop(0);
};
//滚动到底部
const initBottomScroll = () => {
  let clientHei = editTableRef.value!.clientHeight;
  // console.log(clientHei,"全部高度")
  scrollRef.value!.setScrollTop(clientHei);
};

//#endregion

// 获取插槽内容
let slots = useSlots();
// console.log(slots.handle)
// const headers = computed(() => {
//     let headArrNew = props.headData.map(headItem => {
//         let field = headItem.field;
//         let type = props.headConfig[field]?.type || props.headConfig[field];
//         let multiple = props.headConfig[field]?.multiple;

//         return {
//             ...headItem,
//             type: type,
//             isEdit: !!type,
//             multiple: !!multiple,
//             options: props.headConfig[field]?.options,
//             rowClass:false,//列颜色
//         }
//     })
//     return headArrNew;
// });
const headers = ref(null);
// fixedRowsColumns
watch(
  () => props.headData,
  (newValue, oldValue) => {
    console.log("监听值变化，，，，，", newValue);
    // console.log(oldValue);
    let headArrNew = newValue.map(headItem => {
      let type = headItem.type == "multiple" ? "select" : headItem.type;
      let multiple = headItem.type == "multiple" ? true : false;

      return {
        ...headItem,
        type: type,
        isEdit: true,
        multiple: !!multiple
      };
    });
    console.log(headArrNew);
    headers.value = headArrNew;
    if (oldValue && newValue.length > oldValue.length) {
      fixedRowsColumns();
      sumWidth();
    }
  },
  { immediate: true, deep: true }
);

//#region emit监听事件
// emit
const emit = defineEmits<{
  changeSelection: [value: any]; //全选与反选
  editFormFun: [];
}>();
//#endregion

//#region table表格
const allcheckedTd=ref(false);;//是否全部选中
const currentPage = ref(0); //当前页码
const total = ref(0); //总数据
const pageSize = ref(30); //每页展示多少条
const initDataBool = ref(true); //是否是第一次
const newTableDataArr = ref(null); //监听最新数据
const columnsTableData = ref(null); //最后展示数据
const rowItemNew = ref();
watch(
  () => props.tableData,
  (newValue, oldValue) => {
    console.log("监听值变化，，，，，", newValue);
    // console.log(oldValue)
    // if( rowItemNew.value){
    //     rowItemNew.value = "";//清空上次选中值
    // }

    if (props.editStatus) {
      //开启新增删除
      // let editArr = JSON.parse(JSON.stringify(newValue));
      // console.log(editArr)
      let editArrNew = newValue.map((editItem, index) => {
        return {
          ...editItem,
          index: index
        };
      });
      columnsTableData.value = editArrNew;
      console.log(columnsTableData.value);
      return;
    }
    newTableDataArr.value = newValue;

    //开启虚拟加载新增删除
    if (!initDataBool.value) {
      console.log("编辑触发");
      //不是第一次
      let allDataLen = newValue.length;
      let hei = allDataLen * 40;
      if (document.querySelector(".table-wrapper .scroolY")) {
        document.querySelector(".table-wrapper .scroolY").style.cssText = `height: ${hei}px`;
      }
      if (newValue.length > pageSize.value) {
        scrollDirection();
        return;
      }
      let editArr = JSON.parse(JSON.stringify(newValue));
      let editArrNew = editArr.map((editItem, index) => {
        return {
          ...editItem,
          index: index
        };
      });
      columnsTableData.value = JSON.parse(JSON.stringify(editArrNew));
    }

    if (oldValue && newValue.length != oldValue.length) {
      //新增
      initDataBool.value = false;
    }
  },
  { deep: true, immediate: true }
);

//#endregion

//#region 全选与反选
const isIndeterminate = ref(false);
const selectData = ref([]);
const allChecked = ref(false);

//全选
const allCheckedFun = e => {
  let checkBox = !allChecked.value;
  allChecked.value = checkBox; //全选
  isIndeterminate.value = false;
  columnsTableData.value = columnsTableData.value.map(tt => {
    return {
      ...tt,
      selection: checkBox
    };
  });
  if (checkBox) {
    //全部选中
    selectData.value = columnsTableData.value;
  } else {
    selectData.value = [];
  }

  //
  emit("changeSelection", selectData.value);
};

//反选
const checkItemFun = (e, rIndex, rItem) => {
  let selection = !rItem.selection;
  rItem.selection = selection;

  if (selection) {
    //选中塞值
    selectData.value.push(rItem); //当前选中列
  } else {
    //取消删除数组中
    let splitIndex = selectData.value.findIndex((value, index) => {
      return value.selection === false;
    });
    selectData.value.splice(splitIndex, 1);
  }
  isIndeterminate.value = true;

  //所有都选  选中   部分全选补选中
  if (selectData.value.length == columnsTableData.value.length) {
    allChecked.value = true;
    isIndeterminate.value = false;
  } else {
    allChecked.value = false;
    // isIndeterminate.value = false;
    if (selectData.value.length == 0) {
      isIndeterminate.value = false;
    }
  }
  emit("changeSelection", selectData.value);
};

//批量编辑
const moreEditParams = reactive({
  //编辑对象参数
  label: "",
  value: ""
});
const moreEditColumnHeader = ref(null);
const moreEditDialogVisible = ref(false); //弹窗是否显示

const moreEditFun = () => {
  let repateData = false; //是否有重复数据
  selectData.value = []; //清空选中
  let editArrObj = [];
  let selectAllArr = document.querySelectorAll(".selectedRow");
  for (let ss = 0; ss < selectAllArr.length; ss++) {
    // editArrObj.push(JSON.parse(selectAllArr[ss].getAttribute("dataobj")))
    let tdParams = JSON.parse(selectAllArr[ss].dataset.obj);
    if (editArrObj && editArrObj.length > 0) {
      let filterItem = editArrObj.filter(item => item.indexRow == tdParams.indexRow);
      if (filterItem.length > 0) {
        repateData = true;
      } else {
        editArrObj.push(tdParams);
      }
    } else {
      editArrObj.push(tdParams);
    }
  }
  // console.log(repateData, "重复数据");
  // console.log(editArrObj, "触发编辑方法。。。。");
  if (repateData) {
    //有多列请选择一列进行批量编辑
    alert("请选择一列进行批量编辑");
    return;
  }
  //   model
  // console.log( headers.value)
  let headerObj = headers.value.filter(hItem => hItem.key == editArrObj[0].key);
  moreEditColumnHeader.value = headerObj[0]; //获取头部数据哪一列
  moreEditParams.label = "";
  moreEditParams.value = "";
  moreEditDialogVisible.value = true;
  document.querySelector("#context-menu").style.cssText = `display:none;`;

  //  selectData.value
  // columnsTableData.value
  if(allcheckedTd.value){
    // 全部选中
    let allData=JSON.parse(JSON.stringify(newTableDataArr.value));
     selectData.value= allData.map((allItem,index)=>{
    return{
        index:index,
      ...allItem
    }
     });
    return;
  }
  editArrObj.map(eItem => {
    let newArr = columnsTableData.value.filter(cItem => cItem._id == eItem.id);
    selectData.value.push(newArr[0]);
  });
};

const moreEditFormChange = (currVal, type) => {
  moreEditParams.value = currVal;
  if (type == "select") {
    //  let filterArr =moreEditColumnHeader.value.options.filter(oo=>oo.value==value);
    if (moreEditColumnHeader.value.values.length) {
      if (moreEditColumnHeader.value.multiple) {
        //多选
        const array_new = moreEditColumnHeader.value.values.filter(item => currVal.some(ele => ele == item.value));
        let labelArr = [];
        if (array_new.length) {
          array_new.map(newItem => {
            labelArr.push(newItem.label);
          });
          moreEditParams.label = labelArr.join(",");
        }
      } else {
        let optionsArr = moreEditColumnHeader.value.values.find(item => item.value == currVal);
        moreEditParams.label = optionsArr.label;
      }
    }
    return;
  }
  moreEditParams.label = currVal;
};

//批量编辑确认
const confirmEdit = () => {
  // console.log(moreEditColumnHeader.value, "头部");
  // console.log(moreEditParams, "批量编辑后");

  let field = moreEditColumnHeader.value.key;
  // console.log( columnsTableData.value)
  let selectArr = JSON.parse(JSON.stringify(selectData.value));
  console.log(selectArr, "选中值");
  //选中数据
  selectData.value = selectArr.map(sItem => { 
    sItem.data[field] = { label: moreEditParams.label, value: moreEditParams.value };
    return {
      ...sItem
    };
  });
  // console.log(selectData.value, "选中值");

  //页面展示数据
  let fieldFirst = headers.value[0].key;
  let newColumnArr = JSON.parse(JSON.stringify(columnsTableData.value));
  columnsTableData.value = newColumnArr.map(cItem => {
    let haveChacked = selectData.value.filter(ss => ss._id == cItem._id);
    cItem = haveChacked.length > 0 ? haveChacked[0] : cItem; //替换值
    cItem.selection = false;
    return {
      ...cItem
    };
  });
    console.log(columnsTableData.value)
  //全部数据

  let newTableDataArrEdit = JSON.parse(JSON.stringify(newTableDataArr.value));
  newTableDataArr.value = newTableDataArrEdit.map(nItem => {
    let haveChacked = selectData.value.filter(ss => ss._id == nItem._id);
    nItem = haveChacked.length > 0 ? haveChacked[0] : nItem; //替换值

    return {
      ...nItem
    };
  });
  //编辑完后清空
  moreEditDialogVisible.value = false;
  selectData.value = [];

  allcheckedTd.value = false; 
  // clartMouseTd();
  //清楚表头选中
  initResetHeads();
  initResetColumn();
};
//#endregion

// slots.handle

//#region 固定列
let widthArr = [];
const fixedRowsColumns = () => {
  widthArr = [];
  let theadDomArr = document.getElementsByClassName("table-fixed-column-left");
  // console.log(theadDomArr)
  let left = 0;
  for (let pp = 0; pp < theadDomArr.length; pp++) {
    let dom = theadDomArr[pp];
    dom.style.cssText = `left: ${left}px`;
    widthArr.push(left); //所有宽度集合在一个数组中

    let width = dom.getBoundingClientRect().width;
    left = left + width;
    // console.log(theadDomArr[pp].offsetWidth)
    // console.log(dom.getBoundingClientRect().width)
  }
  nextTick(() => {
    allTdLeft();
    if (slots.handle) {
      allTdRight();
    }
  });
};

const allTdLeft = () => {
  let trDom = document.getElementsByClassName("tbody-row");
  for (let trIndex = 0; trIndex < trDom.length; trIndex++) {
    //所有td添加left
    let tdDomArr = trDom[trIndex].children;
    for (let td = 0; td < tdDomArr.length; td++) {
      let tddom = tdDomArr[td];

      let tdIndexOf = tddom.className.indexOf("table-fixed-rows-left");
      if (tdIndexOf != -1) {
        tddom.style.cssText = `left: ${widthArr[td]}px`;
      }
    }
  }
};

//右侧添加阴影
const allTdRight = () => {
  const $firstEl = scrollRef.value.$el.firstElementChild;
  let scrollWidth = document.querySelector(".table-wrapper .scrollTable").scrollWidth;
  let theadDom = document.getElementsByClassName("thead-row"); //thead内容
  let tbodyDom = document.getElementsByClassName("tbody-row"); //tbody内容

  if (scrollWidth - $firstEl.clientWidth > 0) {
    let thFixedRight = theadDom[0].getElementsByClassName("table-cell-fixed-right");
    //添加阴影
    thFixedRight[0].classList.add("table-box-shadow-right");

    for (let trIndex = 0; trIndex < tbodyDom.length; trIndex++) {
      //所有td添加right
      let tdDomArr = tbodyDom[trIndex].getElementsByClassName("table-cell-fixed-right");
      let tddom = tdDomArr[0];
      tddom.classList.add("table-box-shadow-right");
    }
  }
};

const oprationDataFun = (num, type, offsetTop) => {
  // if(buulBool){
  // let num = 3;

  let oprationData = JSON.parse(JSON.stringify(columnsTableData.value)); //展示数组
  // console.log(oprationData)
  let tableAllLen = oprationData.length; //展示数组长度
  let laseIndex = oprationData[tableAllLen - 1].index; // 第一个索引

  // 向下加载
  if (type == "down") {
    // let lastIndex=oprationData[tableAllLen - 1+3].index;
    // console.log(laseIndex)
    // console.log(newTableDataArr.value.length,"==="+laseIndex)
    // console.log(newTableDataArr.value.slice(99, 103))
    let allHei = document.querySelector(".table-wrapper .scroolY").offsetHeight;
    let conHei = document.querySelector(".merak_table.edit_table").offsetHeight;
    // if(allHei-conHei==offsetTop){
    //     // 到达底部
    //     let bottomLen=newTableDataArr.value.length;
    //     let sliceIndex=bottomLen-pageSize.value-1;
    //     let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(sliceIndex, bottomLen)));
    //     let tableDataList = newTableData.map((tt, index) => {
    //         sliceIndex = sliceIndex + 1;
    //         return {
    //             ...tt,
    //             index: sliceIndex
    //         }

    //     })

    //     columnsTableData.value = tableDataList;
    //     return;
    // }
    if (newTableDataArr.value.length > laseIndex + num) {
      let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(laseIndex, laseIndex + num)));
      let tableDataList = newTableData.map((tt, index) => {
        return {
          ...tt,
          index: laseIndex
        };
      });
      oprationData.splice(0, num);
      columnsTableData.value = [...oprationData, ...tableDataList];
    } else {
      if (newTableDataArr.value.length == laseIndex) {
        return;
      }
      let otherLen = newTableDataArr.value.length - laseIndex;
      let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(laseIndex, laseIndex + otherLen)));
      let tableDataList = newTableData.map((tt, index) => {
        return {
          ...tt,
          index: laseIndex
        };
      });

      columnsTableData.value = [...oprationData, ...tableDataList];
    }
    return;
  }

  // 向上加载
  // slice(1,2)  取得是下标为1的数据 第二个

  let firstIndex = oprationData[0].index;
  console.log(firstIndex, "每次第一个");
  if (offsetTop == 0) {
    let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(0, pageSize.value)));
    let sliceLen = newTableData.length;

    let tableDataList = newTableData.map((tt, tIndex) => {
      return {
        ...tt,
        index: tIndex //firstIndex - sliceLen + tIndex
      };
    });
    columnsTableData.value = tableDataList;
    return;
  }
  if (firstIndex - num > 0) {
    let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(firstIndex - num - 1, firstIndex - 1)));

    let sliceLen = newTableData.length;

    let tableDataList = newTableData.map((tt, tIndex) => {
      // 11  14-3+0
      // 12  14-3+1
      // 13  14-3+2
      // 14
      return {
        ...tt,
        index: firstIndex - sliceLen + tIndex - 1
      };
    });
    oprationData.splice(tableAllLen - num, num);
    columnsTableData.value = [...tableDataList, ...oprationData];
  } else {
    console.log("=====chufa");
    if (firstIndex == 1) {
      return;
    }

    let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(0, firstIndex - 1)));
    let sliceLen = newTableData.length;

    let tableDataList = newTableData.map((tt, tIndex) => {
      return {
        ...tt,
        index: firstIndex - sliceLen + tIndex - 1
      };
    });
    columnsTableData.value = [...tableDataList, ...oprationData];
  }
};

// 滚动
let beforeScrollHei = 0; //上一次滚动位置
let interval = null;
//节流数据 向上、向下
const throttle = directionType => {
  // 清楚鼠标移动选中
  clartMouseTd();
  //清楚表头选中
  if(!allcheckedTd.value){
     initResetHeads();
  }
 
  // console.log(beforeScrollHei, numCount + "上次滚动，，，" + scrollTopDiff)
  let scrollTop = document.querySelector(".table-wrapper .el-scrollbar__wrap").scrollTop;
  scrollDirection(directionType);
  if (scrollTop == beforeScrollHei) {
    clearInterval(interval);
    interval = null;
  }
};
//内容滚动到位置
const scrollDirection = () => {
  console.log(selectData.value);
  let oprationData = JSON.parse(JSON.stringify(columnsTableData.value)); //展示数组
  // console.log(oprationData)
  let oprationDataLen = oprationData.length; //展示数组长度

  let scrollTop = document.querySelector(".table-wrapper .el-scrollbar__wrap").scrollTop;
  let clientScrollHei = document.querySelector(".table-wrapper .el-scrollbar").scrollHeight; //滚动区域高度
  let scrollHeight = document.querySelector(".table-wrapper .scroolY").scrollHeight; //滚动所有高度
  let firstNum = Math.ceil(scrollTop / 42);

  if (scrollTop + clientScrollHei >= scrollHeight) {
    let laseIndex = oprationData[oprationDataLen - 1].index; // 当前数组的最后一个索引
    let tableAllLen = newTableDataArr.value.length;
    let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(tableAllLen - pageSize.value, tableAllLen)));

    let selection = allcheckedTd.value; //checkbox选中值
    // let field = headers.value[0].key;
    let tableDataList = newTableData.map((tt, index) => {
      let haveChacked = selectData.value.filter(ss => ss._id == tt._id);
      laseIndex = tableAllLen - newTableData.length + index;
      // tt = haveChacked.length > 0 ? haveChacked[0] : tt; //替换值
      return {
        ...tt,
        index: laseIndex,
        selection: haveChacked.length > 0 || selection
      };
    });
    columnsTableData.value = tableDataList;
    return;
  }
  let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(firstNum, firstNum + pageSize.value)));

  let selection = allcheckedTd.value; //checkbox选中值
  // let field = headers.value[0].key;
  let tableDataList = newTableData.map((tt, index) => {
    let haveChacked = selectData.value.filter(ss => ss._id == tt._id);
    // tt = haveChacked.length > 0 ? haveChacked[0] : tt; //替换值
    return {
      ...tt,
      index: firstNum + index,
      selection: haveChacked.length > 0 || selection
    };
  });
  columnsTableData.value = tableDataList;
};
const scrollFun = scrollVal => {
  //针对当前点击替换class
  if (currTdDom) {
    // console.log(currTdDom)
    currTdDom.classList.remove("active-bg-row-td");
  }
  mearkTable.innerHTML = "";
  //隐藏error错误

  document.querySelector(".table-wrapper .error_div_tip").style.cssText = `display:none;`;
  if (!props.editStatus) {
    //新增、删除禁止编辑
    // console.log(scrollVal)
    let maxHei = document.querySelector(".table-wrapper .scroolY").offsetHeight; //内容区域最大高度
    // console.log(maxHei, "内容区域最大高度")
    let clientScrollHei = document.querySelector(".table-wrapper .el-scrollbar").scrollHeight; //滚动区域高度
    // console.log(clientScrollHei, "滚动区域高度")
    let clientHei = document.querySelector(".table-wrapper .merak_table.edit_table").offsetHeight; //内容课时区域高度
    // console.log(clientHei, "内容课时区域高度")
    let diffHei = clientHei - clientScrollHei;
    // console.log(diffHei, "相差")
    let scrollTop = scrollVal.scrollTop;
    let alreadyScrollTop = scrollTop - diffHei; //上次滚动高度位置
    let scrollDirection = ""; //滚动位置方向
    if (scrollTop - beforeScrollHei > 0) {
      document.querySelector(".merak_table.edit_table").style.cssText = `margin-top: ${scrollTop - diffHei}px`;
      // document.querySelector(".merak_table.edit_table").style.cssText = `top: ${scrollTop-diffHei}px`;
    } else {
      // document.querySelector(".merak_table.edit_table").style.cssText = `top: ${scrollTop}px`;
      document.querySelector(".merak_table.edit_table").style.cssText = `margin-top: ${scrollTop}px`;
    }
    if (interval == null)
      // 未发起时，启动定时器，1秒1执行

      interval = setInterval(() => {
        throttle(scrollDirection);
      }, 500);
    beforeScrollHei = scrollTop;
  }

  // 左侧固定列

  let theadDom = document.getElementsByClassName("thead-row"); //thead内容
  let tbodyDom = document.getElementsByClassName("tbody-row"); //tbody内容
  // thead 固定数量
  let thFixed = theadDom[0].getElementsByClassName("table-cell-fixed");
  if (thFixed.length > 0) {
    //没有固定列
    for (let thIndex = 0; thIndex < thFixed.length; thIndex++) {
      thFixed[thIndex].classList.add("table-box-shadow");
      if (scrollVal.scrollLeft == 0) {
        thFixed[thIndex].classList.remove("table-box-shadow");
      }
    }

    for (let trIndex = 0; trIndex < tbodyDom.length; trIndex++) {
      //所有td添加left
      let tdDomArr = tbodyDom[trIndex].children;
      let tddom = tdDomArr[thFixed.length - 1];
      tddom.classList.add("table-box-shadow");
      if (scrollVal.scrollLeft == 0) {
        tddom.classList.remove("table-box-shadow");
      }
      // tddom.classList.add(boxShadowClassName);
      // tddom.setAttribute("class", boxShadowClassName);
      // let tdIndexOf = tddom.className.indexOf("table-fixed-rows-left");
    }
  }

  // 右侧固定列      if( slots.handle){
  if (scrollVal.scrollLeft > 0 && slots.handle) {
    const $firstEl = scrollRef.value.$el.firstElementChild;
    let offestWidth = $firstEl.scrollWidth - $firstEl.clientWidth - $firstEl.scrollLeft;
    let thFixedRight = theadDom[0].getElementsByClassName("table-cell-fixed-right");
    //添加阴影
    thFixedRight[0].classList.add("table-box-shadow-right");
    if (offestWidth <= 1) {
      // 允许1px的误差
      //滚动到右侧 移除阴影
      thFixedRight[0].classList.remove("table-box-shadow-right");
    }

    for (let trIndex = 0; trIndex < tbodyDom.length; trIndex++) {
      //所有td添加right
      let tdDomArr = tbodyDom[trIndex].getElementsByClassName("table-cell-fixed-right");
      let tddom = tdDomArr[0];
      tddom.classList.add("table-box-shadow-right");
      if (offestWidth <= 1) {
        // 允许1px的误差
        tddom.classList.remove("table-box-shadow-right");
      }
    }
  }
};

//#endregion

//#region 表头点击事件

//#region 编辑事件 双击与单机

const lastClickIndex = ref(undefined); // 上一次点击的索引
const columnCellNew = ref(null); //每一列编辑的数据
const tbodyRef = ref(null);

const rowIndexNew = ref();
const filedKeyNew = ref(""); //当前选中格子key
// 双击
const dbEditClick = (columnItem, rowItem, rowIndex, colIndex, filedKey) => {
  if (!columnItem.isEdit) {
    //不可编辑
    return;
  }
  
  if(columnItem.type=="input"){
    //恢复每行
  initEditRow();
  //td和th添加选中样式
  addTdClass(rowIndex, colIndex);
     rowIndexNew.value = rowIndex;
  rowItemNew.value = rowItem;
  filedKeyNew.value = filedKey;
  rowItem.data[columnItem.key].isEdit = true;
  }
 

  //隐藏error错误
  document.querySelector(".table-wrapper .error_div_tip").style.cssText = `display:none;`;
};
//单击
let setTimerOut=null;
const onceEditClick = ($e, columnItem, rowItem, rowIndex, colIndex, filedKey) => {
  console.log($e, "----");
  console.log(columnItem);
  const { ctrlKey, shiftKey } = $e;

  if (!ctrlKey && !shiftKey) {
    //单纯只进行点击
    // //恢复每行
    if (filedKeyNew.value != filedKey) {
      //点击不是同一行恢复
      initEditRow();
    }
    //重置表头
    initResetHeads();
    initResetColumn();
    // //td和th添加选中样式
    clartMouseTd();
    addTdClass(rowIndex, colIndex);
    if(columnItem.type=="select"){
        rowIndexNew.value = rowIndex;
  rowItemNew.value = rowItem;
  filedKeyNew.value = filedKey;
  rowItem.data[columnItem.key].isEdit = true;
    }
    draggArr.value = [];
  }

  if (ctrlKey) {
    //按住ctrl键

    mearkTable.innerHTML = "";
    //针对当前点击替换class
    if (currTdDom) {
      currTdDom.classList.remove("active-bg-row-td");
    }

    //选中列一致

    if (columnCellNew.value && columnCellNew.value.key == columnItem.key) {
      console.log("选中列一直");
      rowItem.selection = !rowItem.selection;
      columnItem.selection = true;
    } else {
      columnCellNew.value = columnItem;
      // 不一致
      //重置表头
      initResetHeads();
      columnItem.selection = true;

      //重置每行数据
      columnsTableData.value.map(v => {
        v.selection = false;
        return { ...v };
      });
      rowItem.selection = true;
    }

    return;
  }

  if (shiftKey) {
    //按住shift键

    mearkTable.innerHTML = "";
    //针对当前点击替换class
    if (currTdDom) {
      currTdDom.classList.remove("active-bg-row-td");
    }
    //按住shift键
    if (columnCellNew.value && columnCellNew.value.key == columnItem.key) {
      columnItem.selection = true;
    } else {
      //重置表头
      initResetHeads();
      columnItem.selection = true;
      //重置每行数据
      columnsTableData.value.map(v => {
        v.selection = false;
        return { ...v };
      });
    }

    //重置每行数据
    columnsTableData.value.map(v => {
      v.selection = false;
      return { ...v };
    });

    if (lastClickIndex.value && lastClickIndex != rowIndex) {
      let minIndex = 0;
      let maxIndex = 0;
      if (rowIndex < lastClickIndex.value) {
        minIndex = rowIndex;
        maxIndex = lastClickIndex.value + 1;
      } else {
        minIndex = lastClickIndex.value;
        maxIndex = rowIndex + 1;
      }
      columnsTableData.value.slice(minIndex, maxIndex).forEach(item => (item.selection = true));
    }
    lastClickIndex.value = rowIndex;
    return;
  }
  lastClickIndex.value = rowIndex;
};

//重置表头
const initResetHeads = () => {
  headers.value.map(h => {
    h.selection = false;
    return {
      ...h
    };
  });
};

//重置表格内容
const initResetColumn = () => {
  columnsTableData.value.map(c => {
    c.selection = false;
    return {
      ...c
    };
  });
};
//重置样式
const initRowsStyle = () => {
  mearkTable.innerHTML = "";
  //针对当前点击替换class
  if (currTdDom) {
    currTdDom.classList.remove("active-bg-row-td");
  }
};

//#region 移动选中    错误提示

//  isDragging = true;
const isDragging = ref(false);
const handleMouseDown = $e => {
    allcheckedTd.value = false; 
  // console.log($e, "鼠标按下，，，，");
  const { ctrlKey, shiftKey, button } = $e;
  //没有进行键盘选中  //没有右击button=2 右击  button=1中间滚轮  button=0 左击
  if (!ctrlKey && !shiftKey && button == 0) {
    
    isDragging.value = true;
    initResetHeads(); //清除表头
    initResetColumn();
    initRowsStyle();
  }
};
const handleMouseUp = () => {
  // console.log("鼠标抬起，，，，");
  isDragging.value = false;
};
//错误提示
 
const handleMouseOver = e => {
  console.log(e)
  //有错误提示
  if (e.target.parentNode.classList.value.indexOf("err-tip") >= 0 || e.target.classList.value.indexOf("err-tip") >= 0) {
    let td = e.target;
    if (e.target.classList.value.indexOf("cell-nowrap") > 0) {
      td = e.target.parentNode;
    }
    let rect = td.getBoundingClientRect();

    if (td.dataset.obj) {
      let paramsObj = JSON.parse(td.dataset.obj);
      document.querySelector(".err_tip_item").innerText = paramsObj.errTip;

      let offleft = rect.x + rect.width,
        offtop = rect.y;
      document.querySelector(".table-wrapper .error_div_tip").style.cssText = `display:block;left:${offleft}px;top: ${offtop}px`;

      let clientWid = Number(document.querySelector(".merak_table.edit_table")?.clientWidth);
      if (offleft - clientWid >= 0) {
        let errWidth = document.querySelector(".err_cont")?.clientWidth;
        offleft = rect.x - errWidth;
        document.querySelector(".table-wrapper .error_div_tip").style.left = `${offleft}px`;
      }
    }
  }

  
    if (isDragging.value) {
  
   initResetHeads()
    //鼠标按下判断
    let td = e.target; 
    console.log(td)
    if (e.target.classList.value.indexOf("cell-nowrap") >= 0) {
      td = e.target.parentNode;
    }
    if (e.target.parentNode.classList.value.indexOf("cell-nowrap") >= 0) {
      td = e.target.parentNode.parentNode;
    }
    if (td.dataset.obj) {
      let paramsObj = JSON.parse(td.dataset.obj);

      //  headers[paramsObj.key].selection=true;
      let newArr = headers.value.filter(hItem => hItem.key == paramsObj.key);
      if (newArr.length > 0) {
        newArr[0].selection = true;
      }

      let newCArr = columnsTableData.value.filter(cItem => cItem._id == paramsObj.id);
      if (newCArr.length > 0) {
        newCArr[0].selection = true;
      }
    } 
  }
  
};
const handleMouseLeave = e => {
  // console.log(e.target,"鼠标移出")
  document.querySelector(".table-wrapper .error_div_tip").style.cssText = `display:none`;
};
//#endregion

//td和th添加样式
let currTdDom = "";
const addTdClass = (rowIndex, colIndex) => {
  let cellIndex = colIndex;
  if (props.selection) {
    cellIndex = cellIndex + 1;
  }
  if (props.number) {
    cellIndex = cellIndex + 1;
  }

  let headCssActive = `.merak_table thead tr.thead-row>th:nth-child(${cellIndex + 1}){
            background-color:var(--el-color-primary-light-9);
            border-bottom:2px solid var(--el-color-primary);
            box-shadow:none;
        }`;
  let bodyTdCssActive = `
                .merak_table tbody tr.tbody-row:nth-child(${rowIndex + 1})>td:nth-child(1){
                    background-color:var(--el-color-primary-light-9);
                    border-right:2px solid var(--el-color-primary);
                }
               
                `;
  // let currActiveTd = ` .merak_table tbody tr:nth-child(${(rowIndex + 1)}) td:nth-child(${(cellIndex + 1)}){
  //             background-color:var(--el-color-primary-light-9);

  //         }`;
  mearkTable.innerHTML = headCssActive + bodyTdCssActive;
  //针对当前点击替换class
  if (currTdDom) {
    currTdDom.classList.remove("active-bg-row-td");
  }
  let tbodyDom = document.getElementsByClassName("tbody-row"); //tbody内容
  let tddom = tbodyDom[rowIndex].getElementsByClassName("table-cell")[cellIndex];
  currTdDom = tddom;
  tddom.classList.add("active-bg-row-td");

  //重置每行数据
  columnsTableData.value.map(v => {
    v.selection = false;
    return { ...v };
  });
};

//点击行列渲染样式
let mearkTable = document.createElement("style");
mearkTable.id = "markeId";
document.querySelector("body").appendChild(mearkTable);

// 多行选择样式选软
let mearkTableTwo = document.createElement("style");
mearkTableTwo.id = "markeIdTwo";
document.querySelector("body").appendChild(mearkTableTwo);

//点击一列选中
const acticeBgRow = ($e, columnItem, columnIndex) => {
  //针对当前点击替换class
  if (currTdDom) {
    currTdDom.classList.remove("active-bg-row-td");
  }
  allcheckedTd.value=true;//全部选中
  clartMouseTd()
  //重置表头
  initResetHeads();
  columnItem.selection = true;
  initResetColumn();
  columnsTableData.value.map(v => {
    v.selection=true;
    return{
      ...v
    }
  });
 
  // let cellIndex = columnIndex;
  // if (props.selection) {
  //   cellIndex = cellIndex + 1;
  // }
  // if (props.number) {
  //   cellIndex = cellIndex + 1;
  // }

  // let headCssActive = `.merak_table thead tr.thead-row>th:nth-child(${cellIndex + 1}){
  //           background-color:var(--el-color-primary-light-9);
  //           border-bottom:2px solid var(--el-color-primary);
  //           box-shadow:none;
  //               }`;
  // let bodyCssActive = ` .merak_table tbody tr.tbody-row>td:nth-child(${
  //   cellIndex + 1
  // }){background-color:var(--el-color-primary-light-9);
  //                   border-left:2px solid var(--el-color-primary) ;border-right:2px solid var(--el-color-primary);
  //                   border-bottom: 1px solid var(--el-color-primary-light-8);
  //                   }

  //               .merak_table tbody tr.tbody-row:last-child>td:nth-child(${cellIndex + 1}){
  //                   border-bottom:2px solid var(--el-color-primary)
  //               }
  //               `;
  // mearkTable.innerHTML = bodyCssActive;
  // setTimeout(() => {
  //   mearkTable.innerHTML = headCssActive + bodyCssActive;
  // }, 48);
};

const inputRender = (columnItem, rowItem) => {
  console.log(columnItem);
  console.log(slots.tableCol7);

  return h(
    "div",
    { style: "background:skyblue" },
    h("p", null, {
      tableCol7(props) {
        return "我是传进的header插槽内容";
      }
    })
  );
};

//表单事件
const editFormChange = (currVal, columnItem, rowItem, type) => {
  console.log(currVal)
  // console.log(rowItem)
  // console.log(type)
  let trIndex = rowItem.index; //当前数组中索引位置
  const field = columnItem.key;
  rowItem.data[field].value = currVal;
  delete rowItem.data[field].errTip; //删除错误提示
  if (type == "input") {
    rowItem.data[field].label = currVal;
    // emit("editFormFun", JSON.parse(JSON.stringify(rowItem)));
    newTableDataArr.value.splice(trIndex, 1, rowItem); //替换全部数组中的数据

    return;
  }
  if (type == "select") {
    if (columnItem.values.length) {
      if (columnItem.multiple) {
        //多选
        const array_new = columnItem.values.filter(item => currVal.some(ele => ele == item.value));
        let labelArr = [];
        if (array_new.length) {
          array_new.map(newItem => {
            labelArr.push(newItem.label);
          });
          rowItem.data[field].label = labelArr.join(",");
        }
      } else {
        if(currVal){
          let optionsArr = columnItem.values.find(item => item.value == currVal);
        rowItem.data[field].label = optionsArr.label;
        }else{
           rowItem.data[field].label ="";
        }
        
      }
      newTableDataArr.value.splice(trIndex, 1, rowItem); //替换全部数组中的数据

      // emit("editFormFun", JSON.parse(JSON.stringify(rowItem)));
    }
    return;
  }

  if (type == "date") {
    rowItem.data[field].label =
      globalStore.language == "ru" ? dayjs(currVal).format("DD-MM-YYYY") : dayjs(currVal).format("YYYY-MM-DD");
    // emit("editFormFun", JSON.parse(JSON.stringify(rowItem)));
    newTableDataArr.value.splice(trIndex, 1, rowItem); //替换全部数组中的数据
    // console.log(newTableDataArr.value)
    // console.log( props.tableData)
    return;
  }
};

//重置滚动条
const resetScrollSet = () => {
  let newArr = newTableDataArr.value;
  if (!newArr) {
    newArr = columnsTableData.value;
  }
  let hei = newArr.length * 40;
  document.querySelector(".table-wrapper .scroolY").style.cssText = `height: ${hei}px`;
};

//恢复每行
const ininBaseInfo = () => {
  if (rowItemNew.value) {
    rowItemNew.value = ""; //清空上次选中值
  }
};
const initEditRow = () => {
  // 清除之前的选择
  // clartMouseTd();
  if (rowItemNew.value) {
    //row有值替换上一行
    Object.keys(rowItemNew.value.data).map(key => {
      delete rowItemNew.value.data[key].isEdit;
    });
    //针对当前点击替换class
    if (currTdDom) {
      // console.log(currTdDom)
      currTdDom.classList.remove("active-bg-row-td");
    }
    mearkTable.innerHTML = "";
    mearkTableTwo.innerHTML = "";
    columnsTableData.value.splice(rowIndexNew.value, 1, rowItemNew.value);
    rowItemNew.value = ""; //清空上次选中值
  }
};
//关闭编辑事件
const parentEditClose = event => {
  // document.querySelector("body").removeChild( document.getElementById("markeId"));
  const tbodyToHide = tbodyRef.value as HTMLElement;

  if (tbodyToHide && !tbodyToHide.contains(event.target as Node)) {
    // console.log("关闭编辑事件。。。。")
    //恢复每行
    initEditRow();
  }

  const scrollRefHide = document.querySelector(".edit-wrapper");
  if (scrollRefHide && !scrollRefHide.contains(event.target as Node)) {
    // 清除之前的选择
    clartMouseTd();
  }
};
//#endregion

//#region 拖拽
// 拖拽
const startDrag = columnIndex => {
  const startX = event.clientX;
  const startWidth = headers.value[columnIndex]?.width || 200;

  const handleDrag = event => {
    const currentX = event.clientX;
    const diffX = currentX - startX;
    headers.value[columnIndex].width = `${parseInt(startWidth, 10) + diffX}px`;
  };

  const stopDrag = () => {
    document.removeEventListener("mousemove", handleDrag);
    document.removeEventListener("mouseup", stopDrag);
  };

  document.addEventListener("mousemove", handleDrag);
  document.addEventListener("mouseup", stopDrag);
};
//#endregion

//提交表单数据
const submitData = params => {
  let subData = "";
  // let tableData = JSON.parse(JSON.stringify(columnsTableData.value));newTableDataArr.value
  let tableData = JSON.parse(JSON.stringify(newTableDataArr.value));

  if (params) {
    tableData = JSON.parse(JSON.stringify(params));
  }
  if (tableData.length) {
    subData = tableData.map(v => {
      console.log(v);
      let itemObj = {};
      delete v.index;
      delete v.isEdit;
      Object.keys(v.data).map(k => {
        itemObj[k] = typeof v.data[k].value == "string" ? v.data[k].label.trim() : v.data[k].label;
      });

      return {
        ...v,
        data: itemObj
      };
    });
  }
  return subData;
};

//计算第一页展示多少条
const sumCountShowTr = () => {
  let headHei = 40,
    tbodyTrHei = 40;

  if (props.editStatus) {
    //开启新增删除
    // columnsTableData.value =JSON.parse(JSON.stringify(newTableDataArr.value));
    loading.value = false;
    return;
  }
  let hei = newTableDataArr.value.length * tbodyTrHei;
  if (document.querySelector(".table-wrapper .scroolY")) {
    document.querySelector(".table-wrapper .scroolY").style.cssText = `height: ${hei}px`;
    //当前table高度
    let tableBaseOtherHei = document.querySelector(".table-wrapper").offsetHeight;
    //   可绑定数据条数
    let maxNum = Math.ceil(tableBaseOtherHei / 40);
    pageSize.value = maxNum;
    // console.log(maxNum)0-14   14条
    let newTableData = JSON.parse(JSON.stringify(newTableDataArr.value.slice(0, maxNum)));
    let tableDataList = newTableData.map((tt, index) => {
      let pindex = index;
      return {
        ...tt,
        index: pindex
      };
    });

    columnsTableData.value = tableDataList;

    loading.value = false;
  }
};

//计算宽度
const sumWidth = () => {
  if (document.querySelector(".merak_table.edit_table")) {
    let clientAllWidth = Number(document.querySelector(".merak_table.edit_table").clientWidth) - 200;
    let width = clientAllWidth / headers.value.length;
    width = width < 200 ? 200 : width;
    let newHeader = JSON.parse(JSON.stringify(headers.value));
    let newHeaderArr = newHeader.map(h => {
      return {
        ...h,
        width: h.width ?? width
      };
    });
    console.log(newHeaderArr);
    headers.value = newHeaderArr;
  }
};

//清楚鼠标移动选中clartMouseTd
const clartMouseTd = () => {
  //隐藏右击
  document.querySelector("#context-menu").style.cssText = `display:none;`;
  // // 获取表格和单元格
  // const table = document.getElementById("excelTableMerak");
  // const tds = table.getElementsByTagName("td");
  // // 清除之前的选择
  // for (const td of tds) {
  //   td.classList.remove("selectedTd");
  // }
  // mearkTableTwo.innerHTML = "";
};

//窗口监听事件
const handleResize = () => {
  sumCountShowTr();
  sumWidth();
  fixedRowsColumns();
};

let timmer = new Date().getTime();
const loading = ref(true);
onMounted(() => {
  nextTick(() => {
    let now = new Date().getTime();

    sumCountShowTr();
    sumWidth();
    fixedRowsColumns();

    document.addEventListener("click", parentEditClose);

    //监听窗口事件
    window.addEventListener("resize", handleResize);

    document.addEventListener("contextmenu", function (e) {
      e.preventDefault();
      // 其他代码
      if (
        e.target.parentNode.parentNode.classList.value.indexOf("selectedRow") > 0 ||
        e.target.parentNode.classList.value.indexOf("selectedRow") > 0 ||
        e.target.classList.value.indexOf("selectedRow") > 0
      ) {
        document.querySelector("#context-menu").style.cssText = `display:block;top:${e.clientY}px;left:${e.clientX}px;`;
      }
    });
  });
});
onUnmounted(() => {
  console.log("卸载");
  // document.querySelector("body").removeChild(mearkTable);
  let markeId = document.getElementById("markeId");
  console.log(markeId);
  if (markeId) {
    document.querySelector("body").removeChild(markeId);
  }

  // mearkTableTwo

  let markeIdTwo = document.getElementById("markeIdTwo");
  console.log(markeIdTwo);
  if (markeIdTwo) {
    document.querySelector("body").removeChild(markeIdTwo);
  }

  document.removeEventListener("click", parentEditClose);

  //移除监听窗口事件
  window.removeEventListener("resize", handleResize);
});

// 暴露给父组件使用
defineExpose({ editTableRef, submitData, initBottomScroll, initTopScroll, ininBaseInfo, resetScrollSet });
</script>

<style lang="scss">
@import "./index.scss";
@import "./editExcel.scss";
</style>
